package com.neusoft.admin.controller;

import com.neusoft.admin.entity.TableData;
import com.neusoft.grid.entity.AQI;
import com.neusoft.grid.entity.Mission;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.InvalidClassException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class otherViewControl {
    @FXML
    private TableView<TableData> tableView;

    private int count1 = 0;
    private int count2 = 0;
    private double count3 = 0;
    private double count4 = 0;
    private static final String AQI_FILE = "src/com/neusoft/grid/data/AQI.txt";
    // 修正文件路径：确保与实际文件位置匹配
    private static final String MISSION_FILE = "src/com/neusoft/neps/data/missions.txt";
    private int cityCount = 0;
    private int provinceCount = 0;
    private List<AQI> aqilist = new ArrayList<>();

    private static final double TABLE_HEIGHT = 533;
    private static final double TABLE_HEADER_HEIGHT = 30;
    private static final double TABLE_PADDING = 10;

    @FXML
    public void initialize() {
        // 确保在调试模式下运行，查看控制台输出
        System.out.println("===== 程序初始化开始 =====");

        try {
            // 1. 加载AQI数据
            aqilist = loadAQIData();
            System.out.println("加载的AQI记录数: " + aqilist.size());

            // 2. 加载任务数据 - 关键步骤
            List<Mission> missionList = loadMissionData();
            System.out.println("加载的任务记录数: " + missionList.size());

            // 3. 打印前5条任务记录详情
            if (!missionList.isEmpty()) {
                System.out.println("===== 前5条任务记录详情 =====");
                for (int i = 0; i < Math.min(5, missionList.size()); i++) {
                    Mission m = missionList.get(i);
                    System.out.printf("记录 %d: %s | %s | %s | %s | %s%n",
                            i + 1,
                            m.getReporter(),
                            m.getPhone(),
                            m.getGrid(),
                            m.getLocation(),
                            m.getLevel());
                }
            }

            // 4. 计算城市数量
            cityCount = countCities(missionList);
            provinceCount = countProvinces(missionList);
            System.out.println("计算出的城市数量: " + cityCount);

        } catch (IOException e) {
            System.err.println("初始化过程中发生错误: ");
            e.printStackTrace();
            cityCount = 0;
        }

        // 统计AQI数据
        for (AQI aqi : aqilist) {
            if (aqi.getAQI() > 0) count1++;
            if (aqi.getAQI() > 0 && aqi.getAQI() <= 100) count2++;
        }

        count3 = (double) cityCount / 16;
        count4 = (double) provinceCount / 34;

        String formattedProvinceCoverage = String.format("%.2f", count4);
        String formattedCityCoverage = String.format("%.2f", count3);

        // 创建表格数据
        ObservableList<TableData> data = FXCollections.observableArrayList(
                new TableData("空气质量检测总数量", String.valueOf(count1)),
                new TableData("空气质量检测良好数量(1级、2级)", String.valueOf(count2)),
                new TableData("省网格覆盖范围（34个省）", formattedProvinceCoverage),
                new TableData("大城市网格覆盖范围(16个大城市)", formattedCityCoverage));

        tableView.setItems(data);
        setupCellFormatting();

        // 设置表格尺寸
        tableView.setPrefHeight(TABLE_HEIGHT);
        tableView.setMaxHeight(TABLE_HEIGHT);
        tableView.setMinHeight(TABLE_HEIGHT);

        double rowHeight = (TABLE_HEIGHT - TABLE_HEADER_HEIGHT - TABLE_PADDING) / data.size();
        tableView.setFixedCellSize(rowHeight);

        hideVerticalScrollBar();

        System.out.println("===== 程序初始化完成 =====");
    }

    private void hideVerticalScrollBar() {
        Platform.runLater(() -> {
            for (Node node : tableView.lookupAll(".scroll-bar")) {
                if (node instanceof ScrollBar) {
                    ScrollBar scrollBar = (ScrollBar) node;
                    if (scrollBar.getOrientation().equals(javafx.geometry.Orientation.VERTICAL)) {
                        scrollBar.setMaxWidth(0);
                        scrollBar.setVisible(false);
                        scrollBar.setManaged(false);
                    }
                }
            }
        });
    }

    private List<AQI> loadAQIData() throws IOException {
        File file = new File(AQI_FILE);
        System.out.println("[AQI] 文件路径: " + file.getAbsolutePath());
        System.out.println("[AQI] 文件存在: " + file.exists());
        System.out.println("[AQI] 文件大小: " + file.length() + " 字节");

        if (!file.exists() || file.length() == 0) {
            System.err.println("[AQI] 文件不存在或为空");
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return (List<AQI>) ois.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException("[AQI] 数据文件格式错误", e);
        }
    }

    private void setupCellFormatting() {
        for (TableColumn column : tableView.getColumns()) {
            column.setCellFactory(tc -> {
                TableCell cell = new TableCell<TableData, Object>() {
                    @Override
                    protected void updateItem(Object item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setText(null);
                        } else {
                            setText(item.toString());
                            setAlignment(javafx.geometry.Pos.CENTER);
                            setStyle("-fx-font-size: 18px;");
                        }
                    }
                };
                return cell;
            });
        }
    }

    private List<Mission> loadMissionData() throws IOException {
        File file = new File(MISSION_FILE);
        System.out.println("[任务] 文件路径: " + file.getAbsolutePath());
        System.out.println("[任务] 文件存在: " + file.exists());
        System.out.println("[任务] 文件大小: " + file.length() + " 字节");

        if (!file.exists()) {
            System.err.println("[任务] 错误: 文件不存在");
            return new ArrayList<>();
        }

        if (file.length() == 0) {
            System.err.println("[任务] 警告: 文件为空");
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            Object data = ois.readObject();

            if (data instanceof List) {
                List<?> rawList = (List<?>) data;
                if (!rawList.isEmpty() && rawList.get(0) instanceof Mission) {
                    System.out.println("[任务] 成功加载任务数据");
                    return (List<Mission>) data;
                } else {
                    System.err.println("[任务] 错误: 数据格式不正确");
                    System.err.println("首条记录类型: " + (rawList.isEmpty() ? "空列表" : rawList.get(0).getClass().getName()));
                }
            } else {
                System.err.println("[任务] 错误: 文件内容不是列表");
                System.err.println("实际类型: " + data.getClass().getName());
            }

            return new ArrayList<>();
        } catch (ClassNotFoundException e) {
            throw new IOException("[任务] 类未找到: " + e.getMessage(), e);
        } catch (InvalidClassException e) {
            System.err.println("[任务] 序列化版本不匹配: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        } catch (Exception e) {
            System.err.println("[任务] 加载数据时发生未知错误: ");
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    private int countCities(List<Mission> missions) {
        if (missions == null || missions.isEmpty()) {
            System.out.println("[城市统计] 任务列表为空");
            return 0;
        }

        System.out.println("[城市统计] 开始处理 " + missions.size() + " 条记录");

        Set<String> cities = new HashSet<>();
        int processedCount = 0;

        for (Mission mission : missions) {
            // 关键修改：使用grid字段代替location字段
            String gridInfo = mission.getGrid();

            if (gridInfo == null) {
                System.out.println("[城市统计] 跳过空地址记录");
                continue;
            }

            gridInfo = gridInfo.trim();

            if (gridInfo.isEmpty()) {
                System.out.println("[城市统计] 跳过空白地址记录");
                continue;
            }

            System.out.printf("[城市统计] 记录 %d: 原始地址 = '%s'%n", ++processedCount, gridInfo);
            String cityName = extractCityName(gridInfo);

            if (cityName != null && !cityName.isEmpty()) {
                System.out.println("[城市统计] 提取的城市名: " + cityName);
                cities.add(cityName);
            } else {
                System.out.println("[城市统计] 未能提取城市名");
            }
        }

        System.out.println("[城市统计] 最终城市列表: " + cities);
        System.out.println("[城市统计] 唯一城市数量: " + cities.size());

        return cities.size();
    }

    private int countProvinces(List<Mission> missions) {
        if (missions == null || missions.isEmpty()) {
            System.out.println("[省份统计] 任务列表为空");
            return 0;
        }

        System.out.println("[省份统计] 开始处理 " + missions.size() + " 条记录");

        Set<String> provinces = new HashSet<>();
        int processedCount = 0;

        for (Mission mission : missions) {
            String gridInfo = mission.getGrid();

            if (gridInfo == null) {
                System.out.println("[省份统计] 跳过空地址记录");
                continue;
            }

            gridInfo = gridInfo.trim();

            if (gridInfo.isEmpty()) {
                System.out.println("[省份统计] 跳过空白地址记录");
                continue;
            }

            System.out.printf("[省份统计] 记录 %d: 原始地址 = '%s'%n", ++processedCount, gridInfo);
            String provinceName = extractProvinceName(gridInfo);

            if (provinceName != null && !provinceName.isEmpty()) {
                System.out.println("[省份统计] 提取的省名: " + provinceName);
                provinces.add(provinceName);
            } else {
                System.out.println("[省份统计] 未能提取省名");
            }
        }

        System.out.println("[省份统计] 最终省列表: " + provinces);
        System.out.println("[省份统计] 唯一省数量: " + provinces.size());

        return provinces.size();
    }


    private String extractCityName(String gridInfo) {
        // 情况1: 包含空格的格式 (如 "辽宁省 沈阳市")
        if (gridInfo.contains(" ")) {
            String[] parts = gridInfo.split(" ");
            if (parts.length >= 2) {
                return cleanCityName(parts[1]);
            }
        }

        // 情况2: 包含"省"的格式 (如 "辽宁省沈阳市")
        if (gridInfo.contains("省")) {
            int index = gridInfo.indexOf("省");
            if (index > 0 && index < gridInfo.length() - 1) {
                return cleanCityName(gridInfo.substring(index + 1));
            }
        }

        // 情况3: 直接返回清理后的完整字符串
        return cleanCityName(gridInfo);
    }

    private String extractProvinceName(String gridInfo) {
        // 情况1: 包含空格的格式 (如 "辽宁省 沈阳市")
        if (gridInfo.contains(" ")) {
            String[] parts = gridInfo.split(" ");
            if (parts.length >= 1) {
                return cleanProvinceName(parts[0]);
            }
        }

        // 情况2: 包含"省"的格式 (如 "辽宁省沈阳市")
        if (gridInfo.contains("省")) {
            int index = gridInfo.indexOf("省");
            if (index > 0) {
                return cleanProvinceName(gridInfo.substring(0, index));
            }
        }

        // 情况3: 直接返回清理后的完整字符串
        return cleanProvinceName(gridInfo);
    }

    private String cleanCityName(String cityName) {
        // 移除特殊字符和多余后缀（不再截取最后2个字符）
        return cityName
                .replace("市", "")
                .replace("县", "")
                .replace("区", "")
                .replace("特别行政区", "")
                .trim();
    }

    private String cleanProvinceName(String provinceName) {
        // 移除特殊字符和多余后缀
        return provinceName
                .replace("省", "")
                .replace("自治区", "")
                .replace("市", "")
                .replace("特别行政区", "")
                .trim();
    }
}
